//
//  DirectionsViewController.m
//  DNDzgz
//
//  Created by gimenete on 17/05/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "DirectionsViewController.h"
#import "UICRouteAnnotation.h"


@implementation DirectionsViewController

@synthesize target;

- (id)initWithAnnotation:(MyAnnotation *)annotation
{
	self = [super init];
	if(nil != self)
	{
		self.target = annotation;
	}
	
	return self;
}

/*
 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
 - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
 if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
 // Custom initialization
 }
 return self;
 }
 */

- (void)viewDidLoad {
    [super viewDidLoad];
	
	MKCoordinateRegion region;
	MKCoordinateSpan span;
	span.latitudeDelta=0.005;
	span.longitudeDelta=0.005;
	
	CLLocationCoordinate2D location = {target.coordinate.latitude, target.coordinate.longitude};
	region.span=span;
	region.center=location;
	
	routeMapView.delegate = self;
	[routeMapView setRegion:region];
	[routeMapView addAnnotation:target];
	
	centerButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"locatePin.png"]
													style:UIBarButtonItemStyleBordered 
												   target:self 
												   action:@selector(moveToUserLocation)];
	centerButton.enabled = NO;
	self.navigationItem.rightBarButtonItem = centerButton;
}

- (void)moveToUserLocation
{
	[routeMapView setCenterCoordinate:[[[routeMapView userLocation] location] coordinate] animated:YES];
}

- (void)calculateDirections
{
	double lat = [[routeMapView userLocation] coordinate].latitude;
	double lon = [[routeMapView userLocation] coordinate].longitude;
	NSString *startPoint = [[NSString alloc] initWithFormat:@"%f,%f", lat, lon];
	
	lat = target.coordinate.latitude;
	lon = target.coordinate.longitude;
	NSString *endPoint = [[NSString alloc] initWithFormat:@"%f,%f", lat, lon];
	
	UICGDirections *directions = [UICGDirections sharedDirections];
	directions.delegate = self;
	UICGDirectionsOptions *options = [[[UICGDirectionsOptions alloc] init] autorelease];
	
	[directions loadWithStartPoint:startPoint endPoint:endPoint options:options];
	[endPoint release];
	[startPoint release];
}

- (void)directionsDidUpdateDirections:(UICGDirections *)directions {
    // Overlay polylines
    UICGPolyline *polyline = [directions polyline];
    NSArray *routePoints = [polyline routePoints];
	
    routeOverlayView = [[UICRouteOverlayMapView alloc] initWithMapView:routeMapView];
    [routeOverlayView setRoutes:routePoints];
}


#pragma mark <MKMapViewDelegate> Methods
- (void)mapView:(MKMapView *)mapView regionWillChangeAnimated:(BOOL)animated {
	routeOverlayView.hidden = YES;
}

- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated {
	routeOverlayView.hidden = NO;
	[routeOverlayView setNeedsDisplay];
}

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation {
	
	if ([annotation isKindOfClass:[MKUserLocation class]])
	{
		centerButton.enabled = YES;
		[self calculateDirections];
		return nil;
	}
	
	static NSString *identifier = @"RoutePinAnnotation";
	
	if ([annotation isKindOfClass:[UICRouteAnnotation class]]) {
		MKPinAnnotationView *pinAnnotation = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:identifier];
		if(!pinAnnotation) {
			pinAnnotation = [[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:identifier] autorelease];
		}
		
		if ([(UICRouteAnnotation *)annotation annotationType] == UICRouteAnnotationTypeStart) {
			pinAnnotation.pinColor = MKPinAnnotationColorGreen;
		} else if ([(UICRouteAnnotation *)annotation annotationType] == UICRouteAnnotationTypeEnd) {
			pinAnnotation.pinColor = MKPinAnnotationColorRed;
			
		} else {
			pinAnnotation.pinColor = MKPinAnnotationColorPurple;
		}
		
		pinAnnotation.animatesDrop = YES;
		pinAnnotation.enabled = YES;
		pinAnnotation.canShowCallout = YES;
		return pinAnnotation;
	}
	return nil;
}


/*
 // Override to allow orientations other than the default portrait orientation.
 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
 // Return YES for supported orientations
 return (interfaceOrientation == UIInterfaceOrientationPortrait);
 }
 */

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void) mapViewDidFailLoadingMap:(MKMapView *)mapView withError:(NSError *)error
{
	
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
	
	//diretions = nil;
	diretions.delegate = nil;
	[diretions release];
	
	routeMapView.showsUserLocation = NO;
	routeMapView.delegate = nil;
	//routeMapView = nil;
	[routeMapView release];
	
	//target = nil;
	[target release];
	
	if (routeOverlayView != nil) {
		[routeOverlayView release];
	}
	[centerButton release];
    [super dealloc];
}


@end